/*
 * Copyright (C) 2020 Agrui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "stdlib.h"
#include <ArrayList.h>
#include <Registrant.h>
#include <AsyncResult.h>
#include <RegistrantList.h>


RegistrantList* newRegistrantList() {
    RegistrantList* list = (RegistrantList*)malloc(sizeof(RegistrantList));
    if (!list) {
        return NULL;
    }

    list->list = newArrayList();
    if (!list->list) {
        free(list);
        return NULL;
    }

    return list;
}


void registrantListAddRegistrant(RegistrantList* list, Registrant* registrant) {
    if (!list || !registrant) {
        return;
    }
    
    arrayListAdd(list->list, registrant);
}


void registrantListAdd(RegistrantList* list, Handler* h, int what, void* obj) {
    Registrant* registrant;
    
    if (!list) {
        return;
    }

    registrant = newRegistrant(h, what, obj);
    if (!registrant) {
        return;
    }

    registrantListAddRegistrant(list, registrant);
}


static void internalNotifyRegistrants(RegistrantList* list, void* result, int resultSize, int errorCode) {
    if (list && list->list) {
        int i, s;
        for (i = 0, s = arrayListSize(list->list); i < s ; i++) {
             Registrant* r = (Registrant*) arrayListGet(list->list, i);
             internalNotifyRegistrant(r, result, resultSize, errorCode);
        }
    }
}


void registrantListNotifyRegistrants(RegistrantList* list, AsyncResult* ar) {
    internalNotifyRegistrants(list, ar->result, ar->resultSize, ar->errorCode);
}


void deleteRegistrantList(RegistrantList* list) {
    if (list) {
        if (list->list) {
            deleteArrayList(list->list);
            list->list = NULL;
        }
        free(list);
    }
}
